#!/usr/bin/env python2.6

import sys
import json
from optparse import OptionParser
import otter

if __name__ == '__main__':
    usage = "usage: %prog RESOURCE [ARG=VALUE...]"
    parser = OptionParser(usage=usage)
    parser.add_option('-l', '--list',
        action='store_true', help='list resources')
    parser.add_option('-o', '--output',
        help='specify json object path to output, ex. -o request.url')
    options, args = parser.parse_args()

    if options.list:
        print """Resources:
  trackbacks      url,[contains,infonly]   Trackbacks referencing url
  stats           url,[contains]           Count trackbacks
  search          q,[window]               Results matching
  profilesearch   q                        Author profiles matching
  authorsearch    q,[window]               Authors talking about query
  searchcount     q,[window]               Count of results
  linkposts       url,[contains]           Urls posted by author
  linkpostcount   url,[contains]           Count urls posted by author
  urlinfo         url                      Info about url
  authorinfo      url                      Info about author
  tags            url                      Tags for url
  related         url                      Related urls
  trending                                 Trending terms
  toplinks        [contains,window]        Top new links
  toplinkcount    [contains,window]        Count of top new links
List Parameters:
  page,perpage
"""
        sys.exit(0)

    try:
        resource = args[0]
    except IndexError:
        parser.error('must specify resource, use --list to list resources')
    kw = otter.loadrc()
    try:
        kw.update(dict([a.split('=', 1) for a in args[1:]]))
    except ValueError:
        parser.error('bad arg, use: key=value')
    try:
        r = otter.Resource(resource, **kw)
        r() # call the rest api
        print >>sys.stderr, r.url
        o = r.response.o
        if options.output:
            try:
                o = eval('r.%s' % options.output)
                if hasattr(o, 'o'):
                    o = o.o
            except Exception, e:
                parser.error("processing output option: %s: %s" % (options.output, e))
        print json.dumps(o, sort_keys=True, indent=2)
    except Exception, e:
        parser.error(e)
